import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders, HttpEventType } from '@angular/common/http';
import { ToastController, LoadingController } from 'ionic-angular';
import { StorageProvider } from '../storage/storage';

/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {

	public APPLE_ID = "gcgxapp2018123456";
	public APPLE_KEY = "654321ppaxgcg";

	public APP_HTTP_URL = 'http://www.xuanwo123.com';
	public APP_SERVE_URL = '/api/v1';

	//Observable => subscribe
	constructor(
		public http: HttpClient,
		public toastCtrl: ToastController,
		public loadingCtrl: LoadingController,
		public storage: StorageProvider) {
		console.log('Hello HttpProvider Provider');
		this.APP_SERVE_URL = this.APP_HTTP_URL + this.APP_SERVE_URL;
	}

	/**
	 * request请求
	 */
	public postJson(modal: any, action: any, data: any, isload: any) {
		//post提交
		return new Promise((success, complete) => {
			let loading = this.loadingCtrl.create({
				content: '正在请求...'
			});
			//请求状态
			if (isload) {
				loading.present();
			}
			//获取token方式获取数据
			this.getToken().then(token => {
				this.postData(modal, action, data, token).subscribe(res => {
					//非法token
					if (res['status'] == 202) {
						//移除token
						this.storage.removeStorage('token');
					} else {
						if (success)
							success(res)
					}
				}, error => {
					if (isload)
						loading.dismiss();
					this.toastMessage(error.message);
				}, () => {
					if (isload)
						loading.dismiss();
					if (complete)
						complete()
				});
			});
		});
	}

	/**
	 * 重新请求
	 */
	public rePostJson(modal: any, action: any, data: any, isload: any) {

	}

	/**
	 * request请求
	 */
	public postFile(modal: any, action: any, data: any, isload: any) {
		//post提交
		return new Promise((success, complete) => {
			let loading = this.loadingCtrl.create({
				content: '正在请求...'
			});
			//请求状态
			if (isload) {
				loading.present();
			}
			//获取token方式获取数据
			this.getToken().then(token => {
				this.postFileData(modal, action, data, token).subscribe(event => {
					//事件侦听
					if (event.type === HttpEventType.DownloadProgress) {
						// 文件下载进度
						const percentDone = Math.round(100 * event.loaded / event.total);
						console.log(`File is ${percentDone}% uploaded.`);
					} else if (event.type === HttpEventType.UploadProgress) {
						// 文件上传进度
						const percentDone = Math.round(100 * event.loaded / event.total);
						console.log(`File is ${percentDone}% uploaded.`);
					} else if (event instanceof HttpResponse) {
						if (success)
							success(event.body);
					}
				}, error => {
					if (isload)
						loading.dismiss();
					this.toastMessage(error.message);
				}, () => {
					if (isload)
						loading.dismiss();
					if (complete)
						complete()
				});
			});
		});
	}

	/**
	 * 令牌获取
	 */
	private postToken() {
		//登录成功
		return new Promise((success) => {
			let params = {
				"appid": this.APPLE_ID,
				"appkey": this.APPLE_KEY
			};
			//更新token
			this.postData('oauth', 'gettokens', params, "").subscribe(res => {
				if (res['data'] != false) {
					//登录成功
					this.storage.saveStorage('token', { token: res['data'] });
					//保存token
					if (success)
						success(res['data']);
				} else {
					this.toastMessage('token获取异常');
				}
			}, error => {
				//请求异常
				this.toastMessage(error.message);
			}, () => {
				//请求完成
			});
		});
	}

	/**
	 * 请求数据(模块,方法,数据,令牌)
	 */
	private postData(modal: any, action: any, data: any, token: any) {
		//post提交
		let postUrl = this.APP_SERVE_URL;
		if (modal != "")
			postUrl += '/' + modal;
		if (action != "")
			postUrl += '/' + action;
		//发起请求 表单提交
		return this.http.post(postUrl, data, {
			headers: new HttpHeaders({
				"Content-Type": "application/json;charset=utf-8",
				"token": token
			}),
			responseType: 'json'
		});
	}

	/**
	 * 上传文件(模块,方法,数据,令牌)
	 */
	private postFileData(modal: any, action: any, data: any, token: any) {
		//post提交
		let postUrl = this.APP_SERVE_URL;
		if (modal != "")
			postUrl += '/' + modal;
		if (action != "")
			postUrl += '/' + action;
		//开始请求
		return this.http.post(postUrl, data, {
			headers: new HttpHeaders({
				"Content-Type": "application/json;charset=utf-8",
				"token": token
			}),
			observe: 'events',
			reportProgress: true,
			responseType: 'json'
		});
	}

	/**
	 * 获取令牌
	 */
	private getToken() {
		//post提交
		return new Promise((success, complete) => {
			//登录成功
			this.storage.getStorage('token').then(val => {
				//存在性
				if (val == undefined) {
					//获取token
					this.postToken().then(token => {
						if (success)
							success(token);
					});
				} else {
					if (success)
						success(val['token']);
				}
			});
		});
	}

	/**
	 * 消息显示
	 */
	private toastMessage(message: any) {
		//请求异常
		this.toastCtrl.create({
			message: message,
			duration: 2000,
			position: 'top'
		}).present();
	}

}